# coding=utf-8
import re
import time
import requests
from requests.exceptions import ConnectionError, ReadTimeout
from adslproxy.db import RedisClient
from adslproxy.config import *
import platform

if platform.python_version().startswith('2.'):
    import commands as subprocess
elif platform.python_version().startswith('3.'):
    import subprocess
else:
    raise ValueError('python version must be 2 or 3')


class Sender():
    def get_ip(self, ifname=ADSL_IFNAME):
        """
        获取本机IP
        :param ifname: 网卡名称
        :return:
        """
        (status, output) = subprocess.getstatusoutput('ifconfig')
        if status == 0:
            pattern = re.compile(ifname + '.*?inet addr:.*?(\d+\.\d+\.\d+\.\d+).*?P-t-P:', re.S)
            result = re.search(pattern, output)
            if result:
                ip = result.group(1)
                return ip
        else:
            print(output)

    def test_proxy(self, proxy):
        """
        测试代理
        :param proxy: 代理
        :return: 测试结果
        """
        #
        return True

    def remove_proxy(self):
        """
        移除代理
        :return: None
        """
        self.redis = RedisClient()
        self.redis.remove(CLIENT_NAME)
        print('Successfully Removed Proxy')

    def set_proxy(self, proxy):
        """
        设置代理
        :param proxy: 代理
        :return: None
        """
        self.redis = RedisClient()
        if self.redis.set(CLIENT_NAME, proxy):
            print('Successfully Set Proxy', proxy)

    def adsl(self):
        adsl_status = 1 #网卡打开
        """
        拨号主进程
        :return: None
        """
        while True:
            if adsl_status == 1:
                print('Remove Proxy, Please wait')
                try:
                    self.remove_proxy()
                    time.sleep(10)
                except:
                    pass
            while adsl_status == 1:
                print('ADSL stop, Please wait')
                (stop_status, output) = subprocess.getstatusoutput(ADSL_BASH_STOP)
                if stop_status == 0:
                    adsl_status = 0 #关闭网卡
                    time.sleep(10)
                else:
                    time.sleep(2)
            while adsl_status == 0:
                print('ADSL start, Please wait')
                (start_status, output) = subprocess.getstatusoutput(ADSL_BASH_START)
                if start_status == 0:
                    adsl_status = 1 #打开网卡
                    print('ADSL Successfully')
            ip = self.get_ip()
            if ip:
                print('Now IP', ip)
                print('Testing Proxy, Please Wait')
                proxy = '{ip}:{port}'.format(ip=ip, port=PROXY_PORT)
                print(self.test_proxy(proxy))
                if self.test_proxy(proxy):
                    print('Valid Proxy')
                    self.set_proxy(proxy)
                    with open('ip.txt','a+') as f:
                        f.write(proxy+' ' + time.asctime( time.localtime(time.time()) )+ '\n')
                    print('Sleeping')
                    time.sleep(ADSL_CYCLE)
                else:
                    print('Invalid Proxy')
            else:
                print('Get IP Failed, ReDialing')
                adsl_status = 0
                time.sleep(ADSL_ERROR_CYCLE)


def run():
    sender = Sender()
    sender.adsl()


if __name__ == '__main__':
    run()
